package common;

import java.io.Serializable;
import java.security.InvalidParameterException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class Date implements Serializable {
	private static final long serialVersionUID = -3393054040620378548L;
	private int year;
	private int month;
	private int day;
	
	private static final java.text.DateFormat DATE_FORMAT = new java.text.SimpleDateFormat("yy-MM-dd");
	
	public Date(int year, int month, int day) throws InvalidParameterException {
		this.setYear(year);
		this.setMonth(month);
		this.setDay(day);
	}

	public int getYear() {
		return this.year;
	}

	public void setYear(int year) throws InvalidParameterException {
		if(year < 0)
			throw new InvalidParameterException("Anno deve esser maggiore di zero!");
		this.year = year;
	}

	public int getMonth() {
		return month;
	}

	public void setMonth(int month) throws InvalidParameterException {
		if(month < 1 || month > 12)
			throw new InvalidParameterException("Mese non valido! [1-12]");
		this.month = month;
	}

	public int getDay() {
		return day;
	}

	public void setDay(int day) throws InvalidParameterException {
		if(day < 1 || day > 31)
			throw new InvalidParameterException("Giorno non valido! [1-31]");
		this.day = day;
	}

	public String toString() {
		return this.year + "-" + this.month + "-" + this.day;
	}
	
	public int compareTo(Date date) {
		int result = getHourDifference(date);
		
		return result;
	}

	public int getHourDifference(Date date) {
		GregorianCalendar g1 = new GregorianCalendar(this.getYear(), this.getMonth(), this.getDay());
		
        GregorianCalendar g2 = new GregorianCalendar(date.getYear(), date.getMonth(), date.getDay());
        
        long millis = g1.getTimeInMillis() - g2.getTimeInMillis();
        
        return (int) (millis / (1000 * 60 * 60));
	}
	
	public static Date getCurrentDate() {
		GregorianCalendar gc = new GregorianCalendar();
		return new Date(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc.get(Calendar.DAY_OF_MONTH));
	}
	
	public static Date parseDate(String date) throws ParseException {
		GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(DATE_FORMAT.parse(date));
        
		return new Date(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc.get(Calendar.DAY_OF_MONTH));
	}
}
